<?php

namespace app\admin\controller\order;

use app\admin\model\Contrast as contrastModel;
use app\admin\model\Discount;
use app\admin\model\Disrule;
use app\admin\model\Gtype;
use app\admin\model\Member;
use app\admin\model\order\Goods;
use app\admin\model\Userdiscount;
use app\common\controller\Backend;
use think\Db;

/**
 * 订单列管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    protected $noNeedLogin = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("statisList", $this->model->getStatisList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = 'id,ordersn';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['member','discount'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->with(['member','discount'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                if($row->agentid){
                    $member = new Member();
                    $memberItem = $member->getMember($row->agentid,'nickname,username');
                    $row->agentid = $memberItem['username'] ? $memberItem['username'] : $memberItem['nickname'];
                }else{
                    $row->agentid = '暂无上级';
                }
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {

        $gType = new Gtype();
        $gTypeList = $gType->select();

        $disrule = new Disrule();
        $disruleList = $disrule->select();
        if(!$disruleList->isEmpty()){
            foreach ($disruleList as $disruleItem){
                $disruleItem->color = $this->getColor($disruleItem->color);
            }
        }

        if ($this->request->isPost()) {
            $data = $this->request->post("row/a");
            $ogData = [
                'type' => $data['type'],
                'title' => $data['title'],
                'money' => $data['money'],
                'color' => $data['color'],
            ];

            $params = $this->dealAddParam($data);

            if(!is_array($params)){
                $this->error(__('%s Does not exist or has been deleted', $params));
            }

            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }


                    Db::startTrans();
                    $result = $this->model->allowField(true)->save($params);
                    $orderid = $this->model->id;

                    if ($result !== false) {
                        //增加订单商品记录
                        $res = $this->addOrderGoods($ogData,$orderid);
                        if(!is_array($res)){
                            $this->error(__('Parameter %s can not be empty', $res));
                        }
                        //更新优惠券使用记录，金额使用
                        $this->updateStatus($data['discountNum'],$data['code']);
                        Db::commit();
                        $this->success();
                    } else {
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->assignconfig('list',['disruleList'=>$disruleList,'gTypeList'=>$gTypeList]);
        $this->assign('gTypeList',$gTypeList)->assign('disruleList',$disruleList);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $row = $this->dealEditParam($row);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //处理增加的数据
    protected function dealAddParam($data){
        $memberNum = $data['memberNum'];
        //获取用户信息
        $member = new Member();
        $memberItem = $member->getMemberBySn($memberNum,'*');

        if(empty($memberItem)){
            return '用户编号:'.$memberNum;
        }
        //生成订单
        $residue = abs($data['price'] - $data['prepay']);
        $ordersn = 'CSM'.date('YmdHis').$this->random(6);
        $orderData = [
            'openid' => $memberItem['openid'],
            'ordersn' =>$this->checkOrderUniqueness('CSM',$ordersn),
            'agentid' => $memberItem['agentid'],
            'price'=>$data['price'],
            'prepay'=>$data['prepay'],
            'residue'=>$residue,
            'status' =>$data['status'],
        ];


        //使用核销码,优惠券核销
        if($data['discountNum']){
            $discount = new Userdiscount();
            $discountItem = $discount->where('verify',$data['discountNum'])->find();
            if(empty($discountItem)){
                return '优惠券核销码:'.$data['discountNum'];
            }
            $orderData['discount_id'] =$discountItem['id'];
//            //核销优惠券
//            $discountItem->status = 1;
//            $discountItem->verifytime = time();
//            $discountItem->save();
        }

        //使用积分抵用
        if($data['code']){
           $member = new Member();
           $memberCode = $member->field('nickname,credit')->where('creditcode',$data['code'])->find();
           if(!$memberCode->credit){
               return '积分佣金';
           }
            //使用积分金额
           $memberCode = $this->getProportion($memberCode);
           $orderData['touse'] = $memberCode->amount;
//           $memberCode->credit = 0;
//           $memberCode->save();

        }
        return $orderData;
    }
    //处理编辑中订单的数据
    protected function dealEditParam($row){
        //获取购买者信息
        $member = new Member();
        $memberItem = $member->where('openid',$row->openid)->find();
        $row->openidname = $memberItem['username'] ? $memberItem['username'] : $memberItem['nickname'];
        //获取购买者上线
        if($row->agentid){
            $agent = $member->getMember($row->agentid,'username,nickname');
            $row->agentidname = $agent['username'] ? $agent['username'] : $agent['nickname'];
        }else{
            $row->agentidname ='暂无上级';
        }

        if($row->discount_id){
            $userDiscount = new Userdiscount();
            $userDiscountItem = $userDiscount->field('title')->where('id',$row->discount_id)->find();
            $row->discountName = $userDiscountItem->title;
        }else{
            $row->discountName ='未使用优惠券';
        }

        return $row;
    }
    //搜索用户信息
    public function serachMember(){
        if(!$this->request->param('memberNum')){
            return json(['code'=>-1,'msg'=>'缺少参数']);
        }

        $memberNum = trim($this->request->param('memberNum'));

        $member = new Member();
        $memberItem = $member->getMemberBySn($memberNum,'*');
        if(!empty($memberItem)){
            $memberItem->identityname  = $this->getIdentity($memberItem->identity);

            if($memberItem->agentid){
                $agentInfo = $member->getMember($memberItem->agentid);
                $agentInfo->identityname = $this->getIdentity($agentInfo->identity);
            }else{
                $agentInfo = '';
            }

            return json(['code'=>1,'data'=>['member'=>$memberItem,'agentInfo'=>$agentInfo]]);
        }
        return json(['code'=>-1,'msg'=>'用户不存在或已删除']);
    }
    //搜索积分金额
    public function searchCode(){
        if(!$this->request->param('code')){
            return json(['code'=>-1,'msg'=>'缺少参数']);
        }

        $code = trim($this->request->param('code'));
        $member = new Member();

        $memberItem = $member->field('nickname,credit')->where('creditcode',$code)->find();

        if(!empty($memberItem)){
            if(!$memberItem->credit){
                return json(['code'=>-1,'msg'=>'暂无可用积分金额']);
            }
            return json(['code'=>1,'data'=>$this->getProportion($memberItem)]);
        }
        return json(['code'=>-1,'msg'=>'暂无数据']);
    }
    //搜索优惠券
    public function serachDiscount(){
        if(!$this->request->param('discount')){
            return json(['code'=>-1,'msg'=>'缺少参数']);
        }

        $discount = trim($this->request->param('discount'));

        $userDiscount = new Userdiscount();

        $discountItem = $userDiscount->with('discount')->where('verify',$discount)->find();

        if(!empty($discountItem)){
            if($discountItem->status == 2){
                return json(['code'=>1,'data'=>$discountItem]);
            }
            return json(['code'=>-1,'msg'=>'该优惠券已使用']);
        }
        return json(['code'=>-1,'msg'=>'该优惠券不存在或已删除']);
    }

    //增加订单商品表
    protected function addOrderGoods($data,$orderid){

        if(empty($data['color'])){
            return '折扣';
        }

        $color = array_values($data['color']);
        $type = $data['type'];
        $title = $data['title'];
        $money = $data['money'];

        foreach ($color as $key=>$val){
            $ogData = [
                'order_id'=>$orderid,
                'gtype_id' =>$type[$key],
                'name' =>$title[$key],
                'price'=>$money[$key],
                'dis_id'=>$color[$key],
                'createtime'=>time()
            ];

            $orderGoods = new Goods();
            $orderGoods->isUpdate(false)->save($ogData);
            $og[] = $orderGoods->id;
        }
        return $og;
    }
    //身份:1=事业合伙人,2=销售合伙人,3=会员,4=自费会员,5=其他
    //获取用户的身份
    protected function getIdentity($identity){
        switch ($identity){
            case 1:
                return $identity = '事业合伙人';
                break;
            case 2:
                return $identity = '销售合伙人';
                break;
            case 3:
                return $identity = '会员';
                break;
            case 4:
                return $identity = '自费会员';
                break;
            default:
                return $identity = '其他';
        }
    }
    //颜色:1=red,2=yellow,3=purple,4=green,5=white
    protected function getColor($color){
        switch ($color){
            case 1:
                return $color = 'red';
                break;
            case 2:
                return $color = 'yellow';
                break;
            case 3:
                return $color = 'purple';
                break;
            case 4:
                return $color = 'green';
                break;
            default:
                return $color = 'white';
        }
    }
    //验证订单编号的唯一性
    protected function checkOrderUniqueness($prefix,$sn){
        $order = new \app\admin\model\Order();
        $orderItem = $order->where('ordersn',$sn)->find();
        if(!empty($orderItem)){
            return $prefix.date('YmdHis').$this->random(6);
        }
        return $sn;
    }
    //计算积分金额
    protected function getProportion($member){
        $contrast = new contrastModel();
        $contrastItem = $contrast->find();
        $ratio = $contrastItem->ratio / $contrastItem->credit;
        $member->amount = $member->credit * $ratio;
        return $member;
    }

    //修改优惠券使用状态,更新积分金额
    protected function updateStatus($discountNum,$code){
        //核销优惠券
        if($discountNum){
            $discount = new Userdiscount();
            $discountItem = $discount->where('verify',$discountNum)->find();
            $discountItem->status = 1;
            $discountItem->verifytime = time();
            $row = $discountItem->save();
            if($row < 1){
                return false;
            }
        }
        //积分金额
        if($code){
            $member = new Member();
            $memberCode = $member->field('nickname,credit')->where('creditcode',$code)->find();
            $memberCode->credit = 0;
            $row = $memberCode->save();
            if($row < 1){
                return false;
            }
        }
    }

}





























